# -*- coding:utf-8 -*-
from config import CONFIG
from contextlib import closing
import requests, json, os
from time import sleep

# 视频下载

class DouYinDownload(object):

    def __init__(self):
        """
		抖音App视频下载
		"""
        # 无头浏览器
        # chrome_options = Options()
        # chrome_options.add_argument('user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"')
        # self.driver = Browser(driver_name='chrome', executable_path='D:/chromedriver', options=chrome_options, headless=True)


    def read_json_file(self, file_dir_name = ''):
        '''
        读取文件获取json数组
        :param file_dir_name:
        :return:
        '''
        if os.access(file_dir_name, os.R_OK) == False:
            return []
        with open(file_dir_name) as content:
            return json.load(content)
        return []

    def video_download(self, video_url='', save_video_name_dir=''):
        '''
        视频下载
        :param video_url: 视频下载url
        :param save_video_name_dir: 视频下载路径和文件名称 /usr/down/test.mp4
        :return: int 1 下载成功 0 下载失败
        '''
        if os.path.isfile(save_video_name_dir):
            print('log: 下载视频 \r\n %s, \r\n %s 已经存在!' % (save_video_name_dir, video_url))
            return 1

        requests.packages.urllib3.disable_warnings()
        size = content_size = 0
        with closing(requests.get(video_url, stream=True, verify=False)) as response:
            chunk_size = 1024
            content_size = int(len(response.content))

        video_download_success = 0
        try:
            if response.status_code == 200:
                with open(save_video_name_dir, "wb") as file:
                    for data in response.iter_content(chunk_size=chunk_size):
                        file.write(data)
                        size += len(data)
                        file.flush()
            video_download_success = 1
            print('log: 下载视频 \r\n %s, \r\n %s download success!' % (save_video_name_dir, video_url))
        except:
            print('error: 下载视频 \r\n %s \r\n %s download error !' % (save_video_name_dir, video_url))

        return video_download_success


if __name__ == '__main__':
    douyin = DouYinDownload()
    video_url = 'https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0300f980000bdt85qsif32k8lugbgvg&line=0'
    video_save_dir = CONFIG.get_video_dir() + "/" + 'test'
    print(video_save_dir)
    redirect_url = requests.get(video_url)
    print(redirect_url.url)
    exit(1)
    success = douyin.video_download(video_url, video_save_dir)
    print(" 下载结果：%d \r\n 1:success, 0:error" % success)
